package com.langsin.Search;

/**
 * @Auther: MFM
 * @Date: 2021/8/18 - 08 - 18 - 16:28
 * @version: 1.0
 */

public class InsertSearch {

    /**
     * 插值查找   有序
     *
     * @param arr   待查找数组
     * @param left  左索引
     * @param right 右索引
     * @param value 待查找元素
     * @return
     */
    public static int insertSearch(int[] arr, int left, int right, int value) {
        //递归终止条件
        if (left > right) {
            return -1;
        }

        //参数合法性判断
        //待查找元素超出范围
        if (value < arr[0] || value > arr[arr.length - 1]) {
            return -1;
        }

        int mid = left + (right - left) * (value - arr[left]) / (arr[right] - arr[left]);

        int midValue = arr[mid];

        if (value > midValue) {
            //向右递归
            return insertSearch(arr, mid + 1, right, value);
        } else if (value < midValue) {
            //向左递归
            return insertSearch(arr, left, mid - 1, value);
        } else {
            return mid;
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[100];
        for (int i = 0; i < 100; i++) {
            arr[i] = i + 1;
        }
        int index = insertSearch(arr, 0, arr.length - 1, 100);
        if (index == -1) {
            System.out.println("数列中无此元素");
        } else {
            System.out.println("元素下标：" + index);
        }
    }
}
